//
//  ZDRefreshControl.m
//  OCSinaWeiBo
//
//  Created by Apple on 15/11/5.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZDRefreshControl.h"
#import "ZDRefreshView.h"
#import <Masonry/Masonry.h>

#define keyFrame @"frame"

@interface ZDRefreshControl ()

@property (nonatomic, strong) ZDRefreshView *refreshView;

///记录箭头的状态
@property (nonatomic, assign, getter=isUp) BOOL up;

@end

@implementation ZDRefreshControl

- (instancetype)init
{
    self = [super init];
    if (self) {
        
        //隐藏系统自带菊花
        self.tintColor = [UIColor clearColor];
        
        [self prepareUI];
    }
    return self;
}


#warning ZDRefreshControl的init方法内部并不会调用initWithFrame  为什么？
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
        [self prepareUI];
    }
    return self;
}


//准备UI
- (void)prepareUI
{
    //添加子控件
    [self addSubview:self.refreshView];
    
    //添加约束
    [_refreshView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerX.centerY.height.mas_equalTo(self);
        make.width.mas_equalTo(320);
    
    }];
    
    
    //KVO 监听frame的改变
    [self addObserver:self forKeyPath:keyFrame options:NSKeyValueObservingOptionNew context:nil];
}


//KVO回调方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
//    ZDLog(@"%@", change);
    
    if (object != self || ![keyPath isEqual: keyFrame])
    {
        return;
    }
    
    CGRect newFrame = [change[@"new"] CGRectValue];
    
//    ZDLog(@"%@", NSStringFromCGRect(newFrame));
    
    CGFloat offsetY = newFrame.origin.y;
    
    //向上滚动
    if (offsetY > 0)
    {
        return;
    }
    
    //根据系统控件的刷新状态来决定是否刷新
    if (self.refreshing)
    {
        //开始刷新
        [self.refreshView startRefreshing];
    }
    
    if (offsetY < -60 && !self.isUp)
    {
        //箭头向上
//        ZDLog(@"箭头向上");
        
        self.up = YES;
        
        [self.refreshView rotateArrow:self.up];
    }
    else if (offsetY > -60 && self.isUp)
    {
        //箭头向下
//        ZDLog(@"箭头向下");
        
        self.up = NO;
        
        [self.refreshView rotateArrow:self.up];
    }
}


- (void)dealloc
{
    [self removeObserver:self forKeyPath:keyFrame];
}


///重写endRefreshing方法  只有endRefreshing后 tableView才能还原
- (void)endRefreshing
{
    [super endRefreshing];
    
    [self.refreshView stopRefreshing];
}


#pragma mark 懒加载
- (ZDRefreshView *)refreshView
{
    if (!_refreshView)
    {
        _refreshView = [ZDRefreshView refreshView];
    }
    
    return _refreshView;
}

@end
